package com.carmaintain.servlets;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import com.carmaintain.common.Constants;
import com.carmaintain.common.Utils;
import com.carmaintain.config.Configs;
import com.carmaintain.models.ResultObject;

/**
 * Servlet implementation class UploadImage
 */
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print("请使用POST方式调用");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ResultObject result = new ResultObject();
		String fileName = "";
		
		try {
			request.setCharacterEncoding("UTF-8");
			int uploadCount;
			try {
				uploadCount = (Integer)request.getSession().getAttribute(Constants.SESSION_UPLOAD_COUNT);
			} catch (Exception e) {
				uploadCount = 0;
			}
			
			if (uploadCount > Configs.MAX_UPLOAD_TIME) {
				result.setCode(Constants.CODE_EXCEPTION);
				result.setMessage("已达到上传次数上限");
			
				response.setCharacterEncoding("UTF-8");
				response.getWriter().print(Utils.genJsonString(result));
				return;
			}
			
			ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
			sfu.setSizeMax(Configs.MAX_UPLOAD_IMAGE_SIZE);
			List<FileItem> items = sfu.parseRequest(request);
			Iterator<FileItem> fii = items.iterator();
			while(fii.hasNext()) {
				DiskFileItem file = (DiskFileItem)fii.next();
				if(!file.isFormField()&& file.getName().length()>0){//是上传文件的
					String fileSuffix = file.getName().substring(file.getName().lastIndexOf("."));
					if (!".jpg".equalsIgnoreCase(fileSuffix)
							&& !".jpeg".equalsIgnoreCase(fileSuffix)
							&& !".png".equalsIgnoreCase(fileSuffix)) {
						continue;
					}
					
					InputStream in=new BufferedInputStream(file.getInputStream());
					String path = request.getSession().getServletContext().getRealPath(File.separator + Configs.uploadPath);
					//产生UUID来作为名字
					fileName = UUID.randomUUID().toString() + fileSuffix;
					OutputStream out = new BufferedOutputStream(new FileOutputStream(new java.io.File(path+ File.separator  + fileName)));
					byte[] buffer = new byte[1024];
					int count = 0;
					while((count = in.read(buffer)) > 0) {
						out.write(buffer, 0, count);
						out.flush();
					}

					request.getSession().setAttribute(Constants.SESSION_UPLOAD_COUNT, uploadCount + 1);
				}
			}
			result.setCode(Constants.CODE_SUCCESS);
			result.setMessage(Constants.MESSAGE_SUCCESS);
			result.setResultData(fileName);
		} catch (Exception e) {
			result.setCode(Constants.CODE_EXCEPTION);
			result.setMessage(Constants.MESSAGE_EXCETION);
			Utils.addTestMessage(result, e);
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(Utils.genJsonString(result));
	}

}
